import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:math';
import 'package:meco/common/models/browse_record_model.dart';
import 'package:meco/common/models/comment_model.dart';
import 'package:meco/common/data/repositories/comment_repository.dart';
import 'package:uuid/uuid.dart';

/// 初始化数据服务
/// 用于应用第一次启动时初始化基础数据
class InitDataService extends GetxService {
  final UserRepository _userRepository = UserRepository();
  final CeramicRepository _ceramicRepository = CeramicRepository();
  final CeramicStageRepository _ceramicStageRepository =
      CeramicStageRepository();
  final CeramicInteractionRepository _ceramicInteractionRepository =
      CeramicInteractionRepository();
  final OfficialContentRepository _officialContentRepository =
      OfficialContentRepository();
  final RecommendedVideoRepository _videoRepository =
      RecommendedVideoRepository();
  final BrowseRecordRepository _browseRecordRepository =
      BrowseRecordRepository();
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();
  final ChatMessageRepository _chatMessageRepository = ChatMessageRepository();
  final CommentRepository _commentRepository = CommentRepository(
    DatabaseService(),
  );

  // 存储键：是否已初始化数据
  static const String _isDataInitialized = 'is_data_initialized';

  // 存储键：是否已初始化陶瓷数据
  static const String _isCeramicDataInitialized = 'is_ceramic_data_initialized';

  // 存储键：是否已初始化官方内容数据
  static const String _isOfficialContentInitialized =
      'is_official_content_initialized';

  // 存储键：是否已初始化推荐视频数据
  static const String _isVideoDataInitialized = 'is_video_data_initialized';

  // 存储键：是否已初始化聊天数据
  static const String _isChatDataInitialized = 'is_chat_data_initialized';

  // 初始化数据
  Future<void> _initData() async {
    await _initUsers();
    // 未来可以添加其他数据初始化，如文章、评论等
  }

  // 初始化用户
  Future<void> _initUsers() async {
    // 用户名列表 (4-6个英文字符)
    final List<String> usernames = [
      'jack',
      'emma',
      'lucas',
      'olivia',
      'liam',
      'sophia',
      'noah',
      'ava',
      'ethan',
      'mia',
      'logan',
      'lily',
    ];

    // 头像列表
    final List<String> avatars = [
      Images.avatar1,
      Images.avatar2,
      Images.avatar3,
      Images.avatar4,
      Images.avatar5,
      Images.avatar6,
      Images.avatar7,
      Images.avatar8,
      Images.avatar9,
      Images.avatar10,
      Images.avatar11,
      Images.avatar12,
    ];

    // 默认密码
    const String defaultPassword = '123456';

    // 创建12个用户
    for (int i = 0; i < usernames.length; i++) {
      // 添加用户
      final User? user = await _userRepository.register(
        username: usernames[i],
        password: defaultPassword,
        nickname: usernames[i].capitalizeFirst, // 首字母大写作为昵称
      );

      // 如果成功创建用户，则更新头像
      if (user != null) {
        // 由于register方法没有avatar参数，手动更新用户头像
        final updatedUser = user.copyWith(avatar: avatars[i]);
        await _userRepository.updateUser(updatedUser);
      }
    }

    debugPrint('初始用户数据创建完成');
  }

  // 初始化聊天数据
  Future<void> _initChatData() async {
    try {
      // 获取用户列表
      final List<User> users = await _userRepository.getAllUsers();
      if (users.isEmpty || users.length < 6) {
        debugPrint('Unable to initialize chat data: not enough users');
        return;
      }

      final now = DateTime.now();

      // 创建3个群聊
      await _createGroupChat(
        'Exchange of clay and glaze techniques',
        [users[0].id!, users[1].id!, users[2].id!, users[3].id!, users[4].id!],
        [
          _createMessage(
            users[0].id!,
            'Hello everyone, welcome to the Ceramic Art Enthusiasts group!',
            now.subtract(const Duration(days: 2, hours: 5)),
          ),
          _createMessage(
            users[1].id!,
            'Hi! Nice to meet you all',
            now.subtract(const Duration(days: 2, hours: 4, minutes: 50)),
          ),
          _createMessage(
            users[2].id!,
            'I\'m a beginner, are there any recommended resources for getting started?',
            now.subtract(const Duration(days: 2, hours: 4, minutes: 40)),
          ),
          _createMessage(
            users[0].id!,
            'Check out the recommended content on the homepage, there are many great tutorials',
            now.subtract(const Duration(days: 2, hours: 4, minutes: 30)),
          ),
          _createMessage(
            users[3].id!,
            'I\'ve been learning wheel throwing techniques lately, it\'s really challenging',
            now.subtract(const Duration(days: 1, hours: 3)),
          ),
        ],
      );

      await _createGroupChat(
        'Mud Art Research Society',
        [users[5].id!, users[6].id!, users[7].id!, users[8].id!, users[1].id!],
        [
          _createMessage(
            users[5].id!,
            'Hello everyone, this is a vase I recently completed',
            now.subtract(const Duration(days: 3, hours: 7)),
          ),
          _createMessage(
            users[6].id!,
            'Very beautiful, the glaze color is special',
            now.subtract(const Duration(days: 3, hours: 6, minutes: 55)),
          ),
          _createMessage(
            users[7].id!,
            'What kind of glaze did you use?',
            now.subtract(const Duration(days: 3, hours: 6, minutes: 45)),
          ),
          _createMessage(
            users[5].id!,
            'It\'s a homemade celadon glaze, the effect is quite nice',
            now.subtract(const Duration(days: 3, hours: 6, minutes: 30)),
          ),
          _createMessage(
            users[1].id!,
            'I\'m also trying a similar glaze, could you share the formula?',
            now.subtract(const Duration(hours: 12)),
          ),
        ],
      );

      await _createGroupChat(
        'Ceramic Art Sharing Circle',
        [
          users[9].id!,
          users[10].id!,
          users[11].id!,
          users[0].id!,
          users[3].id!,
        ],
        [
          _createMessage(
            users[9].id!,
            'Today\'s lesson is about advanced glazing techniques',
            now.subtract(const Duration(days: 1, hours: 10)),
          ),
          _createMessage(
            users[10].id!,
            'The teacher explained it well, I learned a lot of techniques',
            now.subtract(const Duration(days: 1, hours: 9, minutes: 50)),
          ),
          _createMessage(
            users[0].id!,
            'When is the next class?',
            now.subtract(const Duration(days: 1, hours: 9, minutes: 40)),
          ),
          _createMessage(
            users[9].id!,
            'Next Wednesday at 2PM, the topic will be kiln transformation techniques',
            now.subtract(const Duration(days: 1, hours: 9, minutes: 30)),
          ),
          _createMessage(
            users[3].id!,
            'I\'m looking forward to the kiln transformation class!',
            now.subtract(const Duration(hours: 5)),
          ),
        ],
      );

      // 创建几个单聊
      await _createPrivateChat(users[0].id!, users[1].id!, [
        _createMessage(
          users[0].id!,
          'Hey, what ceramic project are you working on lately?',
          now.subtract(const Duration(days: 1, hours: 8)),
        ),
        _createMessage(
          users[1].id!,
          'I\'m trying to make a tea set, it\'s coming along nicely',
          now.subtract(const Duration(days: 1, hours: 7, minutes: 55)),
        ),
        _createMessage(
          users[0].id!,
          'That\'s great, share it when you\'re done',
          now.subtract(const Duration(days: 1, hours: 7, minutes: 50)),
        ),
      ]);

      await _createPrivateChat(users[2].id!, users[3].id!, [
        _createMessage(
          users[2].id!,
          'Do you know where I can buy good quality clay?',
          now.subtract(const Duration(days: 2, hours: 15)),
        ),
        _createMessage(
          users[3].id!,
          'I usually buy from the ceramic materials store in the east part of town, their clay quality is very consistent',
          now.subtract(const Duration(days: 2, hours: 14, minutes: 50)),
        ),
        _createMessage(
          users[2].id!,
          'Thanks for the recommendation, I\'ll check it out',
          now.subtract(const Duration(days: 2, hours: 14, minutes: 40)),
        ),
      ]);

      debugPrint('Initial chat data creation completed');
    } catch (e) {
      debugPrint('Failed to initialize chat data: $e');
      debugPrintStack();
    }
  }

  // 创建消息辅助方法
  Map<String, dynamic> _createMessage(
    int senderId,
    String content,
    DateTime time,
  ) {
    return {'sender_id': senderId, 'content': content, 'time': time};
  }

  // 创建群聊
  Future<int> _createGroupChat(
    String name,
    List<int> memberIds,
    List<Map<String, dynamic>> messages,
  ) async {
    final now = DateTime.now();

    // 1. 创建聊天室
    final chatRoom = ChatRoom(
      name: name,
      isGroup: true,
      memberIds: memberIds,
      createdAt: now,
      updatedAt: now,
    );

    final chatRoomId = await _chatRoomRepository.createChatRoom(chatRoom);

    // 2. 添加消息
    for (var messageData in messages) {
      final message = ChatMessage(
        chatRoomId: chatRoomId,
        senderId: messageData['sender_id'],
        content: messageData['content'],
        createdAt: messageData['time'],
      );
      await _chatMessageRepository.sendMessage(message);
    }

    return chatRoomId;
  }

  // 创建单聊
  Future<int> _createPrivateChat(
    int user1Id,
    int user2Id,
    List<Map<String, dynamic>> messages,
  ) async {
    final now = DateTime.now();

    // 检查是否已存在这两个用户的单聊
    final exists = await _chatRoomRepository.isChatRoomExist([
      user1Id,
      user2Id,
    ], false);
    if (exists) {
      debugPrint('单聊已存在，跳过创建');
      return -1;
    }

    // 获取用户信息用于聊天室名称
    final user1 = await _userRepository.getUserById(user1Id);
    final user2 = await _userRepository.getUserById(user2Id);
    final chatRoomName =
        '${user1?.nickname ?? 'User'} & ${user2?.nickname ?? 'User'}';

    // 1. 创建聊天室
    final chatRoom = ChatRoom(
      name: chatRoomName,
      isGroup: false,
      memberIds: [user1Id, user2Id],
      createdAt: now,
      updatedAt: now,
    );

    final chatRoomId = await _chatRoomRepository.createChatRoom(chatRoom);

    // 2. 添加消息
    for (var messageData in messages) {
      final message = ChatMessage(
        chatRoomId: chatRoomId,
        senderId: messageData['sender_id'],
        content: messageData['content'],
        createdAt: messageData['time'],
      );
      await _chatMessageRepository.sendMessage(message);
    }

    return chatRoomId;
  }

  // 初始化陶瓷数据
  Future<void> _initCeramicData() async {
    try {
      // 获取用户列表
      final List<User> users = await _userRepository.getAllUsers();
      if (users.isEmpty) {
        debugPrint('无法初始化陶瓷数据：没有可用用户');
        return;
      }

      // 陶瓷图片列表
      final List<String> ceramicImages = [
        Images.ceramic1,
        Images.ceramic2,
        Images.ceramic3,
        Images.ceramic4,
        Images.ceramic5,
        Images.ceramic6,
        Images.ceramic7,
        Images.ceramic8,
      ];

      // 陶瓷标题列表
      final List<String> titles = [
        'Classic Blue Vase',
        'Minimalist Tea Cup',
        'Ancient Pattern Bowl',
        'Modern Sculpture',
        'Traditional Plate',
        'Decorative Pot',
        'Abstract Art Piece',
        'Handcrafted Mug',
      ];

      // 陶瓷描述列表
      final List<String> descriptions = [
        'A beautiful blue vase with traditional glaze techniques. Perfect for displaying fresh flowers or standing alone as a decorative piece.',
        'Simple yet elegant tea cup, designed for everyday use. The minimalist style complements any kitchen decor.',
        'Bowl featuring ancient patterns inspired by historical pottery. Each pattern tells a story of ancient craftsmanship.',
        'A modern interpretation of ceramic art. This sculpture pushes the boundaries of traditional ceramic forms.',
        'Traditional serving plate with intricate hand-painted details. Combines functionality with artistic expression.',
        'Decorative pot with unique texture and color transitions. A statement piece for any room.',
        'An abstract approach to ceramic art, featuring unconventional shapes and bold color choices.',
        'Handcrafted mug with comfortable handle and perfect size. Makes every sip of coffee or tea more enjoyable.',
      ];

      final now = DateTime.now();

      // 创建的陶瓷作品ID列表
      final List<int> ceramicIds = [];

      // 为每个陶瓷图片创建一个陶瓷作品记录
      for (int i = 0; i < ceramicImages.length; i++) {
        // 选择一个随机用户作为创建者
        final User creator = users[i % users.length];

        // 决定是否跳过烧制过程（偶数索引跳过，奇数索引不跳过）
        final bool isSkipped = i % 2 == 0;

        // 创建陶瓷作品
        final Ceramic ceramic = Ceramic(
          userId: creator.id!,
          title: titles[i],
          description: descriptions[i],
          imageUrl: ceramicImages[i],
          isSkipped: isSkipped,
          isCompleted: true,
          createdAt: now.subtract(
            Duration(days: ceramicImages.length - i),
          ), // 创建时间依次递减
          updatedAt: now.subtract(Duration(days: ceramicImages.length - i)),
        );

        // 保存陶瓷作品
        final int ceramicId = await _ceramicRepository.addCeramic(ceramic);
        ceramicIds.add(ceramicId);

        // 如果没有跳过烧制过程，则创建烧制阶段记录
        if (!isSkipped) {
          await _ceramicStageRepository.createStagesForCeramic(ceramicId);

          // 为已创建的烧制阶段设置随机完成状态
          final stages = await _ceramicStageRepository.getStagesByCeramicId(
            ceramicId,
          );
          for (var stage in stages) {
            final stageStartTime = now.subtract(
              Duration(
                days: ceramicImages.length - i,
                hours: stage.type.index * 2,
              ),
            );
            final stageEndTime = stageStartTime.add(Duration(hours: 1));

            // 更新阶段为已完成
            await _ceramicStageRepository.updateStage(
              stage.copyWith(
                status: CeramicStageStatus.completed,
                startTime: stageStartTime,
                endTime: stageEndTime,
                durationSeconds: 3600, // 1小时
              ),
            );
          }
        }
      }

      // 初始化陶瓷浏览记录
      await _initCeramicBrowseRecords(ceramicIds);

      // 初始化陶瓷评论
      await _initCeramicComments(ceramicIds, users);

      debugPrint('初始陶瓷数据创建完成');
    } catch (e) {
      debugPrint('初始化陶瓷数据失败: $e');
    }
  }

  // 初始化陶瓷浏览记录
  Future<void> _initCeramicBrowseRecords(List<int> ceramicIds) async {
    try {
      // 获取所有用户
      final users = await _userRepository.getAllUsers();
      if (users.isEmpty || ceramicIds.isEmpty) {
        debugPrint('无法初始化陶瓷浏览记录：没有用户或陶瓷作品');
        return;
      }

      final now = DateTime.now();
      final random = Random();

      // 为每个陶瓷作品创建随机的浏览记录
      for (int ceramicId in ceramicIds) {
        // 为每个陶瓷作品随机选择4-8个用户进行浏览
        final viewerCount = random.nextInt(5) + 4; // 4到8个用户
        final shuffledUsers = List<User>.from(users)..shuffle();
        final viewers = shuffledUsers.take(viewerCount).toList();

        // 创建浏览记录
        for (int i = 0; i < viewers.length; i++) {
          final user = viewers[i];

          // 浏览时间在过去10天内随机
          final browseTime = now.subtract(
            Duration(
              days: random.nextInt(10),
              hours: random.nextInt(24),
              minutes: random.nextInt(60),
            ),
          );

          // 创建浏览记录
          final record = BrowseRecord(
            userId: user.id!,
            contentId: ceramicId,
            type: BrowseType.ceramic,
            browseTime: browseTime,
          );

          await _browseRecordRepository.addBrowseRecord(record);
        }
      }

      debugPrint('初始陶瓷浏览记录创建完成');
    } catch (e) {
      debugPrint('初始化陶瓷浏览记录失败: $e');
      debugPrintStack();
    }
  }

  // 初始化陶瓷评论
  Future<void> _initCeramicComments(
    List<int> ceramicIds,
    List<User> users,
  ) async {
    try {
      if (users.isEmpty || ceramicIds.isEmpty) {
        debugPrint('无法初始化陶瓷评论：没有用户或陶瓷作品');
        return;
      }

      final random = Random();
      final uuid = Uuid();

      // 陶瓷评论内容列表
      final List<String> commentContents = [
        'The glaze on this piece is absolutely stunning! I love the color transitions.',
        'Such fine craftsmanship, you can really see the attention to detail.',
        'I appreciate the traditional techniques used in creating this piece.',
        'The form is elegant and perfectly balanced. Great work!',
        'I\'m curious about the firing process used for this piece. Was it reduction fired?',
        'The texture on this ceramic is fascinating, how did you achieve that effect?',
        'This reminds me of ancient pottery I saw in a museum exhibition.',
        'Beautiful work! The proportions are perfect.',
        'I love how the glaze pools at the bottom creating that unique effect.',
        'The combination of form and function is excellent in this piece.',
        'What clay body did you use for this? The result is amazing!',
        'The surface decoration complements the form so well.',
        'This piece has such presence! It would be a focal point in any space.',
        'I appreciate the minimalist approach, letting the material speak for itself.',
        'The contrast between the glazed and unglazed portions creates wonderful visual interest.',
        'This shows such mastery of the ceramic medium. Inspiring work!',
      ];

      // 为每个陶瓷作品创建2-5条评论
      for (int ceramicId in ceramicIds) {
        // 随机决定这个作品有几条评论
        final commentCount = random.nextInt(4) + 2; // 2到5条评论

        // 随机选择不同的用户发表评论
        final shuffledUsers = List<User>.from(users)..shuffle();
        final commenters = shuffledUsers.take(commentCount).toList();

        // 创建评论
        for (int i = 0; i < commenters.length; i++) {
          final user = commenters[i];

          // 随机选择一条评论内容
          final commentContent =
              commentContents[random.nextInt(commentContents.length)];

          // 创建时间在过去7天内随机
          final createdAt = DateTime.now().subtract(
            Duration(
              days: random.nextInt(7),
              hours: random.nextInt(24),
              minutes: random.nextInt(60),
            ),
          );

          // 创建评论
          final comment = CommentModel(
            id: uuid.v4(),
            content: commentContent,
            userId: user.id.toString(),
            userName: user.nickname ?? user.username,
            userAvatar: user.avatar ?? Images.avatar1,
            contentId: ceramicId.toString(),
            type: CommentType.ceramic,
            likeCount: random.nextInt(10), // 0-9个点赞
            createdAt: createdAt,
          );

          await _commentRepository.addComment(comment);
        }
      }

      debugPrint('初始陶瓷评论创建完成');
    } catch (e) {
      debugPrint('初始化陶瓷评论失败: $e');
      debugPrintStack();
    }
  }

  // 初始化官方内容
  Future<void> _initOfficialContent() async {
    try {
      final now = DateTime.now();
      final List<int> officialContentIds = [];

      // 第一条官方内容
      int contentId1 = await _createOfficialContent(
        'Artistic expression of ceramics',
        'Not for complicated decoration, but only to present a simple and natural beauty - tea soup is more gentle, life is more pure.',
        Images.officialRelease1,
        now.subtract(const Duration(days: 30)),
      );
      if (contentId1 > 0) officialContentIds.add(contentId1);

      // 第二条官方内容
      int contentId2 = await _createOfficialContent(
        'From clay to porcelain, it is worth collecting',
        'The beauty of porcelain lies in the soul given by fire. Feel its warmth and smoothness with your hands; appreciate its subtle transparency with your eyes.',
        Images.officialRelease2,
        now.subtract(const Duration(days: 25)),
      );
      if (contentId2 > 0) officialContentIds.add(contentId2);

      // 第三条官方内容
      int contentId3 = await _createOfficialContent(
        'Molten clay burns porcelain to bring out the elegance of the world',
        'Ceramics, with the memory of fire and soil, come from the depths of history. In the flow of glaze, it is the immortal elegance given by time.',
        Images.officialRelease3,
        now.subtract(const Duration(days: 20)),
      );
      if (contentId3 > 0) officialContentIds.add(contentId3);

      // 第四条官方内容
      int contentId4 = await _createOfficialContent(
        'One vessel and one object show the style',
        'The life of ceramics starts from a handful of soft clay, passing through the craftsmanship of craftsmen and the tempering of kiln fire, leaving a unique life pattern.',
        Images.officialRelease4,
        now.subtract(const Duration(days: 15)),
      );
      if (contentId4 > 0) officialContentIds.add(contentId4);

      // 第五条官方内容
      int contentId5 = await _createOfficialContent(
        'The precipitation of time and art',
        'The luster and texture of porcelain tell the piety of craftsmen in the pursuit of perfection in the palm of their hands. They are artistic miracles combining rationality and sensibility.',
        Images.officialRelease5,
        now.subtract(const Duration(days: 10)),
      );
      if (contentId5 > 0) officialContentIds.add(contentId5);

      // 第六条官方内容
      int contentId6 = await _createOfficialContent(
        'Taste your life aesthetics',
        'When porcelain is integrated into home decoration, dining tables, tea tables, and living rooms seem to have souls, and elegance and practicality complement each other.',
        Images.officialRelease6,
        now.subtract(const Duration(days: 5)),
      );
      if (contentId6 > 0) officialContentIds.add(contentId6);

      // 获取用户列表用于创建评论
      final List<User> users = await _userRepository.getAllUsers();

      // 初始化官方内容评论
      if (officialContentIds.isNotEmpty && users.isNotEmpty) {
        await _initOfficialContentComments(officialContentIds, users);
      }

      debugPrint('初始官方内容数据创建完成');
    } catch (e) {
      debugPrint('初始化官方内容数据失败: $e');
    }
  }

  // 创建单个官方内容
  Future<int> _createOfficialContent(
    String title,
    String description,
    String imageUrl,
    DateTime publishTime,
  ) async {
    final content = OfficialContent(
      title: title,
      description: description,
      imageUrl: imageUrl,
      publishTime: publishTime,
    );

    return await _officialContentRepository.createOfficialContent(content);
  }

  // 初始化官方内容评论
  Future<void> _initOfficialContentComments(
    List<int> contentIds,
    List<User> users,
  ) async {
    try {
      if (users.isEmpty || contentIds.isEmpty) {
        debugPrint('无法初始化官方内容评论：没有用户或官方内容');
        return;
      }

      final random = Random();
      final uuid = Uuid();

      // 官方内容评论列表（与陶瓷艺术相关的英文评论）
      final List<String> commentContents = [
        'This ceramic art perfectly captures the essence of traditional craftsmanship while adding a modern twist.',
        'The glazing technique shown here reminds me of the Song dynasty porcelain I studied in art history.',
        'I\'m fascinated by how the artist managed to achieve such delicate transitions between colors.',
        'The balance between form and function in this piece is truly remarkable.',
        'As a ceramic enthusiast, I find the firing technique used here particularly interesting.',
        'The cultural heritage represented in this work speaks volumes about ceramic traditions.',
        'I appreciate how this piece honors ancient techniques while exploring contemporary aesthetics.',
        'The texture achieved on this surface is extraordinary - would love to know the process behind it.',
        'This reminds me of the ceramic traditions I encountered during my travels in East Asia.',
        'The interplay of light and shadow on this glazed surface creates a mesmerizing effect.',
        'I\'m impressed by the precision of craftsmanship evident in the details of this work.',
        'This piece demonstrates why ceramic art continues to be relevant in contemporary design.',
        'The artist\'s understanding of material properties really shines through in this creation.',
        'There\'s something meditative about the way this ceramic piece captures stillness and movement.',
        'The combination of traditional clay bodies with modern glazing techniques creates a fascinating contrast.',
        'This work showcases the perfect harmony between artistic expression and technical mastery.',
        'I\'m drawn to the way this piece incorporates natural elements into its design.',
        'The firing process must have been meticulously controlled to achieve these subtle color variations.',
        'As someone learning pottery, this piece gives me inspiration for my own creative journey.',
        'The cultural significance of this ceramic style cannot be overstated - beautiful preservation of heritage.',
      ];

      // 为每个官方内容创建3-6条评论
      for (int contentId in contentIds) {
        // 随机决定这个内容有几条评论
        final commentCount = random.nextInt(4) + 3; // 3到6条评论

        // 随机选择不同的用户发表评论
        final shuffledUsers = List<User>.from(users)..shuffle();
        final commenters = shuffledUsers.take(commentCount).toList();

        // 创建评论
        for (int i = 0; i < commenters.length; i++) {
          final user = commenters[i];

          // 随机选择一条评论内容
          final commentContent =
              commentContents[random.nextInt(commentContents.length)];

          // 创建时间在过去14天内随机
          final createdAt = DateTime.now().subtract(
            Duration(
              days: random.nextInt(14),
              hours: random.nextInt(24),
              minutes: random.nextInt(60),
            ),
          );

          // 创建评论
          final comment = CommentModel(
            id: uuid.v4(),
            content: commentContent,
            userId: user.id.toString(),
            userName: user.nickname ?? user.username,
            userAvatar: user.avatar ?? Images.avatar1,
            contentId: contentId.toString(),
            type: CommentType.officialContent,
            likeCount: random.nextInt(15), // 0-14个点赞
            createdAt: createdAt,
          );

          await _commentRepository.addComment(comment);
        }
      }

      debugPrint('初始官方内容评论创建完成');
    } catch (e) {
      debugPrint('初始化官方内容评论失败: $e');
      debugPrintStack();
    }
  }

  // 将资源文件复制到本地临时目录
  Future<String?> _copyAssetToLocal(String assetPath) async {
    try {
      // 获取临时目录
      final tempDir = await getTemporaryDirectory();

      // 提取文件名
      final fileName = assetPath.split('/').last;
      final localPath = '${tempDir.path}/$fileName';

      // 检查文件是否已存在
      final file = File(localPath);
      if (await file.exists()) {
        debugPrint('文件已存在，直接使用: $localPath');
        return localPath;
      }

      // 读取资源文件
      final data = await rootBundle.load(assetPath);
      final bytes = data.buffer.asUint8List();

      // 写入本地文件
      await file.writeAsBytes(bytes);

      debugPrint('资源文件复制成功: $localPath');
      return localPath;
    } catch (e) {
      debugPrint('复制资源文件失败: $e');
      return null;
    }
  }

  // 生成视频缩略图
  Future<String?> _generateVideoThumbnail(String videoPath) async {
    try {
      final tempDir = await getTemporaryDirectory();
      final fileName = DateTime.now().millisecondsSinceEpoch.toString();
      final thumbnailPath = '${tempDir.path}/$fileName.jpg';

      // 获取完整的视频路径
      String? fullVideoPath = videoPath;

      // 如果是assets路径，需要先将资源复制到临时目录
      if (videoPath.startsWith('assets/')) {
        debugPrint('视频是资源文件，尝试复制到本地: $videoPath');
        fullVideoPath = await _copyAssetToLocal(videoPath);

        if (fullVideoPath == null) {
          debugPrint('复制资源文件失败，无法生成缩略图');
          return null;
        }
      }

      // 使用video_thumbnail生成缩略图
      final thumbnailFile = await VideoThumbnail.thumbnailFile(
        video: fullVideoPath,
        thumbnailPath: thumbnailPath,
        imageFormat: ImageFormat.JPEG,
        quality: 75,
      );

      debugPrint('视频缩略图生成成功: $thumbnailFile');
      return thumbnailFile;
    } catch (e) {
      debugPrint('生成视频缩略图失败: $e');
      return null;
    }
  }

  // 初始化推荐视频数据
  Future<void> _initVideoData() async {
    try {
      // 视频描述列表（英文，与陶瓷主题相关）
      final List<String> descriptions = [
        'Traditional Pottery Wheel Techniques: From Clay to Art',
        'The Art of Ceramic Glazing: How Artisans Bring Life to Their Creations',
        'Thousand-Year Kiln Fire: Exploring Traditional Wood-Firing Process in Jingdezhen',
        'Modern Ceramic Innovation: Perfect Blend of Tradition and Contemporary Aesthetics',
        'Porcelain Craftsmanship: The Delicate Process of Fine China Production',
        'Raku Firing Demonstration: The Ancient Japanese Ceramic Technique',
        'Ceramic Sculpture Mastery: Creating Expressive Forms with Clay',
      ];

      // 视频地址列表
      final List<String> videoUrls = [
        Images.video1,
        Images.video2,
        Images.video3,
        Images.video4,
        Images.video5,
        Images.video6,
        Images.video7,
      ];

      // 默认缩略图列表（使用陶瓷图片）
      final List<String> defaultThumbnails = [
        Images.ceramic1,
        Images.ceramic2,
        Images.ceramic3,
        Images.ceramic4,
        Images.ceramic5,
        Images.ceramic6,
        Images.ceramic7,
      ];

      // 创建的视频ID列表
      final List<int> videoIds = [];

      // 添加7个示例视频
      for (int i = 0; i < descriptions.length; i++) {
        // 尝试生成视频缩略图
        final thumbnailUrl = await _generateVideoThumbnail(videoUrls[i]);

        // 如果缩略图生成失败，使用默认图片
        final finalThumbnailUrl = thumbnailUrl ?? defaultThumbnails[i];

        final videoId = await _createRecommendedVideo(
          descriptions[i],
          finalThumbnailUrl,
          videoUrls[i],
        );

        if (videoId > 0) {
          videoIds.add(videoId);
        }
      }

      // 初始化视频浏览记录
      await _initVideoBrowseRecords(videoIds);

      debugPrint('初始推荐视频数据创建完成');
    } catch (e) {
      debugPrint('初始化推荐视频数据失败: $e');
      // 打印堆栈跟踪以便调试
      debugPrintStack();
    }
  }

  // 创建单个推荐视频
  Future<int> _createRecommendedVideo(
    String description,
    String thumbnailUrl,
    String videoUrl,
  ) async {
    try {
      final video = RecommendedVideo(
        description: description,
        thumbnailUrl: thumbnailUrl,
        videoUrl: videoUrl,
      );

      final id = await _videoRepository.createRecommendedVideo(video);
      return id;
    } catch (e) {
      debugPrint('创建单个视频失败: $e');
      return -1;
    }
  }

  // 初始化视频浏览记录
  Future<void> _initVideoBrowseRecords(List<int> videoIds) async {
    try {
      // 获取所有用户
      final users = await _userRepository.getAllUsers();
      if (users.isEmpty || videoIds.isEmpty) {
        debugPrint('无法初始化视频浏览记录：没有用户或视频');
        return;
      }

      final now = DateTime.now();
      final random = Random();

      // 为每个视频创建随机的浏览记录
      for (int videoId in videoIds) {
        // 为每个视频随机选择3-6个用户进行浏览
        final viewerCount = random.nextInt(4) + 3; // 3到6个用户
        final shuffledUsers = List<User>.from(users)..shuffle();
        final viewers = shuffledUsers.take(viewerCount).toList();

        // 创建浏览记录
        for (int i = 0; i < viewers.length; i++) {
          final user = viewers[i];

          // 浏览时间在过去7天内随机
          final browseTime = now.subtract(
            Duration(
              days: random.nextInt(7),
              hours: random.nextInt(24),
              minutes: random.nextInt(60),
            ),
          );

          // 创建浏览记录
          final record = BrowseRecord(
            userId: user.id!,
            contentId: videoId,
            type: BrowseType.video,
            browseTime: browseTime,
          );

          await _browseRecordRepository.addBrowseRecord(record);
        }
      }

      debugPrint('初始视频浏览记录创建完成');
    } catch (e) {
      debugPrint('初始化视频浏览记录失败: $e');
      debugPrintStack();
    }
  }

  // 强制重新初始化数据（用于开发测试或首次安装应用）
  Future<void> resetAndInitData() async {
    try {
      debugPrint('开始初始化应用数据...');

      // 重置初始化标志
      await StorageUtils.setBool(_isDataInitialized, false);
      await StorageUtils.setBool(_isCeramicDataInitialized, false);
      await StorageUtils.setBool(_isOfficialContentInitialized, false);
      await StorageUtils.setBool(_isVideoDataInitialized, false);
      await StorageUtils.setBool(_isChatDataInitialized, false);

      // 初始化用户数据
      debugPrint('初始化用户数据...');
      await _initUsers();

      // 初始化陶瓷数据
      debugPrint('初始化陶瓷作品数据...');
      await _initCeramicData();

      // 初始化官方内容
      debugPrint('初始化官方内容数据...');
      await _initOfficialContent();

      // 初始化视频数据
      debugPrint('初始化推荐视频数据...');
      await _initVideoData();

      // 初始化聊天数据
      debugPrint('初始化聊天数据...');
      await _initChatData();

      // 标记为已初始化
      await StorageUtils.setBool(_isDataInitialized, true);
      await StorageUtils.setBool(_isCeramicDataInitialized, true);
      await StorageUtils.setBool(_isOfficialContentInitialized, true);
      await StorageUtils.setBool(_isVideoDataInitialized, true);
      await StorageUtils.setBool(_isChatDataInitialized, true);

      debugPrint('所有应用数据初始化完成');
    } catch (e) {
      debugPrint('初始化数据过程中发生错误: $e');
      // 打印堆栈跟踪以便调试
      debugPrintStack();
      rethrow; // 重新抛出错误，以便调用者知道初始化失败
    }
  }
}
